package com.crowd.web.config;

import com.crowd.entity.Admin;
import com.crowd.entity.Auth;
import com.crowd.entity.Role;
import com.crowd.service.api.IAdminService;
import com.crowd.service.api.IAuthService;
import com.crowd.service.api.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Stone
 * @date 2020/6/3 21:51
 */
@Component
public class CrowdUserDetailsService implements UserDetailsService {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IAuthService authService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.根据username找admin
        Admin admin = adminService.getAdminByLoginAcct(username);
        Integer adminId = admin.getId();
        // 3.根据adminId找角色
        List<Role> roleList = roleService.getAssignedRoleList(adminId);
        // 4.根据adminId找权限
        List<String> authList = authService.getAssignedAuthNameByAdminId(adminId);

        List<GrantedAuthority> authorities =  new ArrayList<>();
        // 5.遍历roleList，然后把roleName放在List<GrantedAuthority>
        for (Role r:roleList){
            String roleName = "ROLE_" + r.getName();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            authorities.add(simpleGrantedAuthority);
        }
        // 6.遍历authList，然后把roleName放在List<GrantedAuthority>
        for(String authName:authList){
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);
            authorities.add(simpleGrantedAuthority);
        }

        // 7.封装到SecurityAdmin
        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);
        return securityAdmin;
    }
}
